{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-02-12T03:17:45.908955Z",
     "start_time": "2020-02-12T03:17:45.891912Z"
    },
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# 如果k <= (n-1)!, 则开头数字为1，\n",
    "# 如果1*(n-1)! < k <= 2*(n-1)!, 则开头数字为2，其他依次类推。\n",
    "import pdb\n",
    "#pdb.set_trace()\n",
    "\n",
    "class Solution:\n",
    "    def getPermutation(self, n: int, k: int) -> str:\n",
    "        mul = [1]\n",
    "        out = \"\"\n",
    "        remain = [x for x in range(1,n+1)]\n",
    "        k -= 1\n",
    "        for i in range(1, n+1):\n",
    "            mul.append(mul[-1]*i)\n",
    "        for e in mul[-2::-1]:\n",
    "            idx, k = divmod(k, e) #注意这里的k-1\n",
    "            out += str(remain.pop(idx))\n",
    "        return out\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-02-12T03:17:47.921551Z",
     "start_time": "2020-02-12T03:17:47.917896Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12345\n"
     ]
    }
   ],
   "source": [
    "a = Solution()\n",
    "print(a.getPermutation(5,1))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "308.4px",
    "left": "747px",
    "right": "20px",
    "top": "87px",
    "width": "492.4px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
